package com.fayou.algorithm.queue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AxinBlockQueue1<T> {

    private List<T> container = new ArrayList<>();
    private Lock lock = new ReentrantLock();
    private Condition isNull = lock.newCondition();
    private Condition isFull = lock.newCondition();

    private volatile int size;

    private volatile int capacity;

    public AxinBlockQueue1(int capacity) {
        this.capacity = capacity;
    }


    public void add(T data) {
        try {
            lock.lock();
            try {
                while (size >= capacity) {
                    System.out.println("阻塞队列满");
                    isFull.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                isFull.signal();
            }
            ++size;
            container.add(data);
            isNull.signal();
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }


    public T take() {
        try {
            lock.lock();

            try {
                while (size == 0) {
                    System.out.println("队列数据为空");
                    isNull.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                isNull.signal();
            }
            --size;
            T data = container.remove(0);

            isFull.signal();
            return data;

        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
        return null;
    }


    public void qkSort(int[] data, int start, int end) {
        if (data == null || data.length == 0) {
            return;
        }
        if (start>end){
            return;
        }
        int left = start;
        int right = end;

        int temp = data[start];

        while (left < right) {
            while (left < right && data[right] > temp) {
                right--;
            }

            data[left] = data[right];
            while (left < right && data[left] <= temp) {
                left++;
            }
            data[right] = data[left];
        }

        data[left] = temp;

        qkSort(data, start, left - 1);
        qkSort(data, left + 1, end);
    }
}
